<template>
  <el-button type="success" @click="dialogVisible = true">新增</el-button>

  <el-table :data="tableData" style="width: 100%">
    <el-table-column type="index" label="编号" width="100" />
    <el-table-column prop="userName" label="用户名" width="120" />
    <el-table-column prop="roleName" label="角色名称" width="120" />
    <el-table-column prop="sex" label="性别" width="120">
      <template v-slot="scope">
        <el-tag v-if="scope.row.sex == 0">男</el-tag>
        <el-tag v-if="scope.row.sex == 1">女</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="shnegid" label="所在省份" width="120" />
    <el-table-column prop="shiId" label="所在市" width="120" />
    <el-table-column prop="xianId" label="所在县" width="120" />
    <el-table-column prop="addDesc" label="地址详情" width="120">
      <template v-slot="scope">
        <div class="row center">
          <el-tooltip
            class="box-item"
            effect="dark"
            :content="scope.row.addDesc"
            placement="top-start"
          >
            <span>{{ scope.row.addDesc.slice(0, 5) + "..." }}</span>
          </el-tooltip>
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="createName" label="创建人" width="120" />
    <el-table-column prop="createTime" label="创建日期" width="200">
      <template v-slot="scope">
        <span>{{
          moment(scope.row.createTime).format("YYYY-MM-DD HH:mm:ss")
        }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="updateName" label="修改人" width="120" />
    <el-table-column prop="updateTime" label="修改日期" width="200">
      <template v-slot="scope">
        <span v-if="scope.row.updateTime == null"></span>
        <span v-else>{{
          moment(scope.row.updateTime).format("YYYY-MM-DD HH:mm:ss")
        }}</span>
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作" min-width="160">
      <template v-slot="scope">
        <el-button type="primary" @click="edit(scope.row)"> 修改 </el-button>
        <el-button type="danger" @click="deluser(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!--  新增用户 -->
  <el-dialog v-model="dialogVisible" title="新增用户" width="500">
    <el-form
      ref="ruleFormRef"
      style="max-width: 1000px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="ruleForm.userName" />
      </el-form-item>
      <el-form-item label="性别" prop="resource">
        <el-radio-group v-model="ruleForm.sex">
          <el-radio :value="1">女</el-radio>
          <el-radio :value="0">男</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="所在地区">
          <el-col :span="8">
            <el-select placeholder="请选择省份" @change="handleProvinceChange" v-model="ruleForm.shnegid" >
            <el-option v-for="a in provinceList" :key="a.value" :label="a.label" :value="a.label" />
          </el-select>
          </el-col>
          <el-col :span="8">
            <el-select placeholder="请选择市" @change="handleCityChange" v-model="ruleForm.shiId" >
            <el-option v-for="a in cityList" :key="a.value" :label="a.label" :value="a.label" />
          </el-select>
          </el-col>
          <el-col :span="8">
            <el-select placeholder="请选择县" v-model="ruleForm.xianId" >
            <el-option v-for="a in districtList" :key="a.value" :label="a.label" :value="a.label" />
          </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="所属部门" prop="bid">
        <el-select v-model="ruleForm.bid" placeholder="请选择部门">
          <el-option
            v-for="a in budata"
            :label="a.departmentName"
            :value="a.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="详细地址" prop="addDesc">
        <el-input v-model="ruleForm.addDesc" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          保存
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <!-- 修改用户 -->
  <el-dialog v-model="dialogVisible1" title="修改用户" width="500">
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForms"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="ruleForms.userName" />
      </el-form-item>
      <el-form-item label="性别" prop="resource">
        <el-radio-group v-model="ruleForms.sex">
          <el-radio :value="1">女</el-radio>
          <el-radio :value="0">男</el-radio>
        </el-radio-group>
      </el-form-item>
       <el-form-item label="所在地区">
          <el-col :span="8">
            <el-select placeholder="请选择省份" @change="handleProvinceChange" v-model="ruleForms.shnegid" >
            <el-option v-for="a in provinceList" :key="a.value" :label="a.label" :value="a.label" />
          </el-select>
          </el-col>
          <el-col :span="8">
            <el-select placeholder="请选择市" @change="handleCityChange" v-model="ruleForms.shiId" >
            <el-option v-for="a in cityList" :key="a.value" :label="a.label" :value="a.label" />
          </el-select>
          </el-col>
          <el-col :span="8">
            <el-select placeholder="请选择县" v-model="ruleForms.xianId" >
            <el-option v-for="a in districtList" :key="a.value" :label="a.label" :value="a.label" />
          </el-select>
          </el-col>
        </el-form-item>
      <el-form-item label="所属部门" prop="bid">
        <el-select v-model="ruleForms.bid" placeholder="请选择部门">
          <el-option
            v-for="a in budata"
            :label="a.departmentName"
            :value="a.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="详细地址" prop="addDesc">
        <el-input v-model="ruleForms.addDesc" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForms(ruleFormRef)">
          保存
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <div class="demo-pagination-block">
    <tr>
      <td>
        <el-pagination
          v-model:current-page="page.Index"
          v-model:page-size="page.Size"
          :page-sizes="[15, 20]"
          :background="true"
          layout="slot, sizes"
          :total="page.count"
        >
          <span
            >共{{ page.count }}条，{{ page.Index }}/{{ page.pcount }}页</span
          >
        </el-pagination>
      </td>
      <td>
        <el-pagination
          v-model:current-page="page.Index"
          v-model:page-size="page.Size"
          :page-sizes="[15, 20]"
          :background="true"
          prev-text="上一页"
          next-text="下一页"
          layout="slot, prev, pager, next"
          :total="page.count"
        >
          <button @click="page.Index = 1">首页</button>
        </el-pagination>
      </td>
      <td>
        <el-pagination
          v-model:current-page="page.Index"
          v-model:page-size="page.Size"
          :page-sizes="[15, 20]"
          :background="true"
          layout="slot,  jumper"
          :total="page.count"
        >
          <button @click="page.Index = page.pcount">尾页</button>
        </el-pagination>
      </td>
    </tr>
  </div>
</template>

<script lang="ts" setup>
import axios from "axios";
import { onMounted, ref, watch } from "vue";
import { regionData, codeToText } from 'element-china-area-data'
import read from '../../http/AxiosHelper';
import write from '../../http/AxiosHelper1';
onMounted(() => {
  getuser();
  getdepartment();
});
const handleClick = () => {
  console.log("click");
};
//分页数据
const page = ref({
  Index: 1,
  Size: 15,
  count: 0,
  pcount: 0,
});
//列表数据
const tableData = ref([]);
//显示列表方法
const getuser = () => {
  read
    .get("/api/User/GetUser", { params: page.value })
    .then((res) => {
      tableData.value = res.data.datas;
      page.value.count = res.data.totalCount;
      page.value.pcount = res.data.totalPage;
    });
};
//监听
watch(page.value, () => {
  getuser();
},{deep:true});
//添加弹出框
const dialogVisible = ref(false);
import { reactive } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";

import { routerViewLocationKey, useRouter } from "vue-router";
const router = useRouter();
import moment from "moment";

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
  userName: "",
  sex: "",
  pwd:"",
  shnegid: "",
  shiId: "",
  xianId: "",
  bid: "",
  addDesc: "",
});
const ruleForms = reactive({
  id: "",
  userName: "",
  sex: "",
  pwd:"",
  shnegid: "",
  shiId: "",
  xianId: "",
  bid: "",
  addDesc: "",
});

const locationOptions = ["Home", "Company", "School"];

const rules = reactive({
  id: [{ required: true, message: "编号不能为空", trigger: "blur" }],
  userName: [
    {
      required: true,
      message: "用户名不能为空",
      trigger: "change",
    },
  ],
  addDesc: [
    {
      required: true,
      message: "详细地址不能为空",
      trigger: "change",
    },
  ],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      write
        .post("/api/User/AddUser", ruleForm)
        .then((res) => {
          if (res.data.code == 200) {
            ElMessage.success(res.data.msg);
            dialogVisible.value = false;
            ruleForm.addDesc = "";
            ruleForm.sex = "";
            ruleForm.shnegid = "";
            ruleForm.shiId = "";
            ruleForm.userName = "";
            ruleForm.bid = "";
            ruleForm.xianId = "";
            getuser();
          } else {
            ElMessage.error(res.data.msg);
          }
        });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}));

// 省份列表
const provinceList = regionData
// 城市列表
const cityList = ref<any[]>([])
// 区县列表
const districtList = ref<any[]>([])

// 使用你指定的ID名称


// 省份改变时，加载对应城市
const handleProvinceChange = (provinceCode: string) => {
  ruleForm.shiId=''
  ruleForm.xianId=''

  
  const province = regionData.find(item => item.label === provinceCode)
  if (province && province.children) {
    cityList.value = province.children
  } else {
    cityList.value = []
  }
}

// 城市改变时，加载对应区县
const handleCityChange = (cityCode: string) => {
  ruleForm.xianId=''
  
  const province = regionData.find(item => item.label === ruleForm.shnegid)
  if (province) {
    const city = province.children?.find(item => item.label === cityCode)

    if (city?.children) {
      districtList.value = city.children
    } else {
      districtList.value = []
      console.warn('当前城市无区县数据')
    }
  }
}
console.log(regionData);
//修改反填
const dialogVisible1 = ref(false);
const edit = async (row: any) => {
  dialogVisible1.value = true;
  Object.assign(ruleForms, row);
};
const submitForms = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      write
        .put("/api/User/UpdateUser", ruleForms)
        .then((res) => {
          if (res.data.code == 200) {
            ElMessage.success(res.data.msg);
            dialogVisible1.value = false;
            ruleForms.addDesc = "";
            ruleForms.sex = "";
            ruleForms.shnegid = "";
            ruleForms.shiId = "";
            ruleForms.userName = "";
            ruleForms.xianId = "";
            ruleForms.bid = "";
            getuser();
          } else {
            ElMessage.error(res.data.msg);
          }
        });
    } else {
      console.log("error submit!", fields);
    }
  });
};
//删除
const deluser = (id: any) => {
  if (!confirm("确定要删除吗")) {
    return;
  }
  write
    .put("/api/User/DelUser", { id: id })
    .then((res) => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg);
        getuser();
      } else {
        ElMessage.error(res.data.msg);
      }
    });
};

//部门下拉框
const budata = ref();
const getdepartment = () => {
  read
    .get("/api/Department/GetDepartment")
    .then((res) => {
      budata.value = res.data.data;
    });
};
</script>
